package com.sc.adminspringboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sc.adminspringboot.dto.AdminDTO;
import com.sc.adminspringboot.pojo.Admins;
import com.sc.adminspringboot.service.IAdminsService;
import com.sc.adminspringboot.utils.JwtUtils;
import com.sc.adminspringboot.utils.ResponseMsg;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员基础信息表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2025-09-20 09:11:50
 */
@RestController
@RequestMapping("/admin")
public class AdminsController {

    @Autowired
    private IAdminsService adminsService;

    /**
     * 管理员登录接口
     * @param admin 包含adminAccount和adminPassword的管理员对象
     * @return 登录结果和JWT token
     */
    @PostMapping("/login")
    public ResponseMsg login(@RequestBody Admins admin) {
        System.out.println("登录请求参数：" + admin);
        // 检查请求参数是否为空
        if (admin == null || admin.getAdminAccount() == null || admin.getAdminPassword() == null) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "账号和密码不能为空");
        }

        // 根据账号查找管理员
        Admins dbAdmin = adminsService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Admins>()
                        .eq("admin_account", admin.getAdminAccount())
        );

        // 检查管理员是否存在
        if (dbAdmin == null) {
            return ResponseMsg.getInstance(ResponseMsg.ACCOUNT_ERROR, "账号不存在");
        }

        // 对传入的密码进行MD5加密并验证
        String encryptedPassword = DigestUtils.md5DigestAsHex(admin.getAdminPassword().getBytes());
        if (!dbAdmin.getAdminPassword().equalsIgnoreCase(encryptedPassword)) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "密码错误");
        }

        // 检查账号状态
        if (dbAdmin.getStatus() != 1) {
            return ResponseMsg.getInstance(ResponseMsg.Status_ERROR, "账号已被禁用");
        }

        // 更新最后登录时间
        dbAdmin.setLastLoginTime(new Date());
        adminsService.updateById(dbAdmin);

        // 生成JWT token
        Map<String, Object> tokenData = new HashMap<>();
        tokenData.put("admin_id", dbAdmin.getAdminId());
        tokenData.put("admin_account", dbAdmin.getAdminAccount());
        tokenData.put("admin_role", dbAdmin.getAdminRole());
        tokenData.put("admin_name", dbAdmin.getAdminName());

        String token = JwtUtils.createJWT(
                UUID.randomUUID().toString(),
                com.alibaba.fastjson.JSON.toJSONString(tokenData),
                3600 * 24 * 1000 // 24小时过期
        );

        // 将token添加到JwtUtils中
        JwtUtils.addToken(dbAdmin.getAdminAccount(), token);

        // 返回成功响应和token
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("token", token);
        responseData.put("admin", dbAdmin);

        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "登录成功", responseData);
    }
    @GetMapping("/check")
    public ResponseMsg checkTokenValidity(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "未提供Token");
        }

        token = token.substring(7); // 去掉 "Bearer "
        try {
            // 验证 token 是否有效
            Claims claims = JwtUtils.parseJWT(token);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "Token有效");
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "Token无效或已过期");
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public ResponseMsg getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "未提供Token");
        }
        System.out.println("获取当前用户");
        token = token.substring(7); // 去掉 "Bearer "
        try {
            // 解析 token 获取用户信息
            Claims claims = JwtUtils.parseJWT(token);
            String subject = claims.getSubject();
            Map<String, Object> userInfo = com.alibaba.fastjson.JSON.parseObject(subject, Map.class);
            System.out.println("用户信息：" + userInfo);
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "获取用户信息成功", userInfo);
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "Token无效或已过期");
        }
    }

    /**
     * 获取管理员列表
     */
    @GetMapping("/list")
    public ResponseMsg getAdminList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            System.out.println(keyword);
            // 构建查询条件
            QueryWrapper<Admins> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("admin_id");
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("admin_account", keyword)
                        .or()
                        .like("admin_name", keyword);
            }

            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("admin_account", keyword)
                        .or()
                        .like("admin_name", keyword);
            }

            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Admins> pageParam =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);

            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Admins> result =
                    adminsService.page(pageParam, queryWrapper);

// 转换为 AdminDTO 对象，屏蔽密码字段
            List<AdminDTO> dtoList = result.getRecords().stream().map(admin -> {
                AdminDTO dto = new AdminDTO();
                dto.setAdminId(admin.getAdminId());
                dto.setAdminAccount(admin.getAdminAccount());
                dto.setAdminRole(admin.getAdminRole());
                dto.setAdminName(admin.getAdminName());
                dto.setCreateTime(admin.getCreateTime());
                dto.setLastLoginTime(admin.getLastLoginTime());
                dto.setStatus(admin.getStatus());
                dto.setResetPasswordTime(admin.getResetPasswordTime());
                return dto;
            }).collect(Collectors.toList());

            Map<String, Object> data = new HashMap<>();
            data.put("list", dtoList);
            data.put("total", result.getTotal());

            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "获取管理员列表成功", data);
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "获取管理员列表失败");
        }
    }

    /**
     * 添加管理员
     */
    @PostMapping("/add")
    public ResponseMsg addAdmin(@RequestBody Admins admin) {
        try {
            // 检查账号是否已存在
            Admins existingAdmin = adminsService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Admins>()
                            .eq("admin_account", admin.getAdminAccount())
            );

            if (existingAdmin != null) {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "账号已存在");
            }

            // 加密密码
            admin.setAdminPassword(DigestUtils.md5DigestAsHex(admin.getAdminPassword().getBytes()));
            admin.setCreateTime(new Date());
            admin.setStatus((byte) 1); // 默认启用

            boolean success = adminsService.save(admin);
            if (success) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "添加管理员成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "添加管理员失败");
            }
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "添加管理员失败");
        }
    }

    /**
     * 更新管理员信息
     */
    @PutMapping("/update")
    public ResponseMsg updateAdmin(@RequestBody Admins admin) {
        try {
            // 如果密码不为空，则加密密码
            if (admin.getAdminPassword() != null && !admin.getAdminPassword().trim().isEmpty()) {
                admin.setAdminPassword(DigestUtils.md5DigestAsHex(admin.getAdminPassword().getBytes()));
            } else {
                // 如果密码为空，则不更新密码字段
                admin.setAdminPassword(null);
            }

            boolean success = adminsService.updateById(admin);
            if (success) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "更新管理员信息成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "更新管理员信息失败");
            }
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "更新管理员信息失败");
        }
    }

    /**
     * 删除管理员
     */
    @DeleteMapping("/delete/{adminId}")
    public ResponseMsg deleteAdmin(@PathVariable Integer adminId) {
        try {
            boolean success = adminsService.removeById(adminId);
            if (success) {
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "删除管理员成功");
            } else {
                return ResponseMsg.getInstance(ResponseMsg.ERROR, "删除管理员失败");
            }
        } catch (Exception e) {
            return ResponseMsg.getInstance(ResponseMsg.ERROR, "删除管理员失败");
        }
    }
}
